import csv
import re
import sys
import tkinter as tk
from io import StringIO
from tkinter import ttk, scrolledtext
from bs4 import BeautifulSoup
from datetime import datetime


class ConsoleRedirector:
    """重定向控制台输出到文本框"""

    def __init__(self, text_widget):
        self.text_widget = text_widget

    def write(self, message):
        self.text_widget.insert(tk.END, message)
        self.text_widget.see(tk.END)
        self.text_widget.update_idletasks()


def parse_html_to_csv(html_content, csv_path, output_widget):
    soup = BeautifulSoup(html_content, "lxml")

    main_section = soup.find('div', class_=re.compile('interview-list-C'))
    if not main_section:
        print("未找到数据主区域")
        return

    date_blocks = main_section.find_all('ul', class_=re.compile('interview-of-date'))
    output_widget.write(f"发现 {len(date_blocks)} 个日期区块\n")
    data = []
    for block in date_blocks:
        date_section = block.find_previous('div', class_=re.compile('interview-date'))
        date_text = "未知日期"
        if date_section:
            date_text = ' '.join(date_section.stripped_strings)
            date_match = re.search(r'(\d{2})月\s*(\d{2})日', date_text)
            if date_match:
                date_text = f"2025-{date_match.group(1)}-{date_match.group(2)}"

        items = block.find_all('div', class_=re.compile('content item disabled'))
        print(f"在 {date_text} 发现 {len(items)} 个条目")

        for item in items:
            # 修改电话字段处理逻辑
            phone_element = item.select_one('[class*="phone"]')
            phone = f"'{phone_element.get_text(strip=True)}" if phone_element else ""

            record = {
                "日期": date_text,
                "时间": item.select_one('[class*="time-content"]').get_text(strip=True) if item.select_one(
                    '[class*="time-content"]') else "",
                "姓名": item.select_one('[class*="geek-name"]').get_text(strip=True) if item.select_one(
                    '[class*="geek-name"]') else "",
                "岗位": ' '.join(item.select_one('[class*="geek-position"]').stripped_strings) if item.select_one(
                    '[class*="geek-position"]') else "",
                "电话": phone  # 已添加单引号前缀
            }
            data.append(record)

    try:
        data.sort(key=lambda x: datetime.strptime(x["日期"], "%Y-%m-%d"))
    except:
        data.sort(key=lambda x: x["日期"])

    if data:
        with open(csv_path, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.DictWriter(f, fieldnames=data[0].keys())
            writer.writeheader()
            writer.writerows(data)
        print(f"成功导出 {len(data)} 条记录到 {csv_path}")
    else:
        print("没有提取到有效数据")


def main():
    # 创建主窗口
    root = tk.Tk()
    root.title("面试数据提取器 v1.0")
    root.geometry("800x600")

    # 创建控件
    frame = ttk.Frame(root, padding=10)
    frame.pack(fill=tk.BOTH, expand=True)

    text_area = scrolledtext.ScrolledText(frame, wrap=tk.WORD)
    text_area.pack(fill=tk.BOTH, expand=True)

    # 重定向标准输出
    sys.stdout = ConsoleRedirector(text_area)

    # 操作按钮
    def start_process():
        try:
            html_content = pyperclip.paste()
            parse_html_to_csv(html_content, "面试数据.csv", sys.stdout)
        except Exception as e:
            print(f"发生错误: {str(e)}")

    btn = ttk.Button(frame, text="开始处理剪贴板内容", command=start_process)
    btn.pack(pady=10)

    root.mainloop()


if __name__ == "__main__":
    import pyperclip

    main()